const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const glob = require("glob");

module.exports = (async function () {

  const entries = await getEntries();

  return {
    entry: entries,
    mode: "development",
    externals: {
      antd: "antd",
      react: "react"
    },
    output: {
      library: '[name]',
      libraryTarget: 'umd',
      filename: '[name]/index.js',
      path: path.resolve(__dirname, "es")
    },
    resolve: {
      extensions: ['.tsx', '.ts', '.js'],
    },
    module: {
      rules: [ 
        {
          test: /\.tsx?$/,
          use: ['babel-loader', 'ts-loader'],
          exclude: /node_modules/,
        },
        {
          test: /\.(le|c)ss$/i,
          use: [
            {
              loader: MiniCssExtractPlugin.loader
            },
            {
              loader: "css-loader"
            },
            {
              loader: 'postcss-loader',
              options: {
                postcssOptions: {
                  plugins: ['autoprefixer'],
                },
                sourceMap: true,
              },
            },
            // 将 less 编译成 CSS
            'less-loader'
          ],
        },
        {
          test: /\.(gif|jpg|png)$/,
          loader: "file-loader",
          options: {
            name: '[name].[ext]',
            outputPath: "images",
            publicPath: "../images"
          }
        },
        {
          test: /\.(ttf|woff|woff2)$/,
          loader: "file-loader",
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts',
            publicPath:"../fonts"
          }
        }
      ]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new MiniCssExtractPlugin({
        filename: "[name]/style.css"
      })
    ]
  };

}())


/**
 * 获取按需加载的入口
 */
function getEntries () {
  return new Promise((resolve) => {
    const module = {};
    glob("./src/components/**/*.tsx", (err, files) => {
      files.forEach((file) => {
        const array = file.split("/");
        const name = array[array.length - 2];
        module[name] = file;
      })
      resolve(module);
    })
  })
}


getEntries();